<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="100px">
            <el-form-item label="适用区域" prop="regionId">
                <el-select clearable v-model="queryParams.regionId" @change="searchRegionChange">
                    <el-option v-for="(item, index) of regionOption" :key="index" :label="item.label"
                        :value="item.value">{{ item.label }}
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="门店" prop="storeId">
                <el-select clearable v-model="queryParams.storeId">
                    <el-option v-for="(item, index) of searchStoreOption" :key="index" :label="item.label"
                        :value="item.value">{{ item.label }}
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="下单时间" prop="time">
                <el-date-picker v-model="time" style="width: 240px" :picker-options="pickerOptions"
                    value-format="yyyy-MM-dd" type="daterange" @change="getTime" range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                    v-hasPermi="['business:coupondetailed:query']">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane label="收入" name="first"></el-tab-pane>
            <el-tab-pane label="支出" name="second"></el-tab-pane>
        </el-tabs>
        <el-row :gutter="10" class="mb8">
            <!-- <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:user:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:user:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:user:remove']"
            >删除</el-button
          >
        </el-col> -->
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['business:storedSalesRanking:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-if="activeName == 'first'" v-loading="loading" :data="storeList" max-height="650px"
            @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="100" align="center" /> -->
            <!-- <el-table-column label="编号" align="center" prop="storeId" /> -->
            <el-table-column label="归属门店" align="center" prop="storeName" />
            <el-table-column label="总收入" align="center" prop="totalIncome" />
            <el-table-column label="服务项目收入" align="center" prop="itemIncome" />
            <el-table-column label="附加商品收入" align="center" prop="itemIncome" />
            <el-table-column label="包间收入" align="center" prop="compartmentIncome" />
            <el-table-column label="储值卡购卡收入" align="center" prop="valueCardIncome" />
            <el-table-column label="会员卡购卡收入" align="center" prop="memberCardIncome" />
            <el-table-column label="资源占用费收入" align="center" prop="sourceUseFee" />
            <el-table-column label="收支类型中参与统计的收入" align="center" prop="statisticIncome" />
        </el-table>

        <el-table v-else v-loading="loading" :data="storeList" max-height="650px"
            @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="100" align="center" /> -->
            <!-- <el-table-column label="编号" align="center" prop="num" /> -->
            <el-table-column label="归属门店" align="center" prop="storeName" />
            <el-table-column label="总支出" align="center" prop="totalExpend" />
            <el-table-column label="员工工资" align="center" prop="staffSalary" />
            <el-table-column label="技师工资" align="center" prop="techSalary" />
            <el-table-column label="储值卡退款金额" align="center" prop="valueCardRefund" />
            <el-table-column label="附加商品成本" align="center" prop="productCost" />
            <el-table-column label="收支类型中支出" align="center" prop="statisticExpend" />
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改用户对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { delUser, addUser, updateUser } from "@/api/system/user";
import { queryProfitAndExpend } from "@/api/statistics";
import { fetchRegionList, fetchStoreList } from "@/api/system/orderList/order";

export default {
    name: "User",
    data() {
        return {
            activeName: "second", //tab页
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 用户表格数据
            storeList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                storeId: null,
                regionId: null,
                startTime: null,
                endTime: null,
                orderId: null,
                technicianName: null,
                userName: null,
                phoneNumber: null,
                couponName: null,
                discountsType: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {},
            regionOption: [], // 区域下拉框
            storeOption: [], // 门店下拉框
            searchStoreOption: [],
            regionId: "",
            regionName: "",
            storeId: "",
            storeName: "",
            //预约时间
            pickerOptions: {
                shortcuts: [
                    {
                        text: "当日",
                        onClick(picker) {
                            picker.$emit("pick", [new Date(), new Date()]);
                        },
                    },
                    {
                        text: "昨日",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "当月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date(end.getFullYear(), end.getMonth(), 1);
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "上月",
                        onClick(picker) {
                            // const end = new Date();
                            const start = new Date();
                            // start.setMonth(start.getMonth() - 1); // 设置开始时间为上月同一天
                            // start.setDate(end.getDate()); // 确保开始时间和结束时间在同一天
                            start.setMonth(start.getMonth() - 1, 1); // 设置开始时间为上月1号
                            const end = new Date(start.getFullYear(), start.getMonth() + 1, 0); // 获取上月的最后一天
                            picker.$emit("pick", [start, end]);
                        },
                    },
                ],
            },
            time: [],
            type: "", //优惠券类型
        };
    },
    created() {
        this.getList();
        this.getRegionOption();
        this.type = this.$route.query.type;
    },
    methods: {
        // tab切换
        handleClick(tab, event) {
            console.log(tab, event);
            this.activeName = tab.name;
            this.getList();
        },
        /** 查询用户列表 */
        getList() {
            this.loading = true;
            queryProfitAndExpend(this.queryParams).then((response) => {
                this.storeList = response.rows;
                this.total = response.total;
                this.loading = false;
            })
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                storeId: null,
                regionId: null,
                id: null,
                userId: null,
                userName: null,
                avatar: null,
                sex: null,
                birthday: null,
                phoneNumber: null,
                status: null,
                openId: null,
                createTime: null,
                updateTime: null,
                isDelete: null,
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
            this.time = [];
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加用户";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getUser(id).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = "修改用户";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.id != null) {
                        updateUser(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addUser(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm('是否确认删除用户编号为"' + ids + '"的数据项？')
                .then(function () {
                    return delUser(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            let url = "";
            if (this.activeName == "first") {
                url = "statistics/valueCardSellStoreExport";
            } else {
                url = "statistics/valueCardSellStaffExport";
            }
            this.download(
                url,
                {
                    ...this.queryParams,
                },
                `user_${new Date().getTime()}.xlsx`
            );
        },
        // 获取归属区域下拉数据
        getRegionOption() {
            fetchRegionList().then((res) => {
                this.regionOption = res.data.map((rItem) => {
                    return {
                        value: rItem.id,
                        label: rItem.regionName,
                    };
                });
            });
        },
        // 归属区域切换
        regionChange(value) {
            const selectedOption = this.regionOption.find(
                (item) => item.value === value
            );
            this.regionId = value;
            this.regionName = selectedOption.label;
            if (value) {
                this.queryParams.storeId = "";
            }
            fetchStoreList({ regionId: value }).then((res) => {
                this.storeOption = res.data.map((rItem) => {
                    return {
                        label: rItem.storeName,
                        value: rItem.id,
                    };
                });
            });
        },
        // 归属门店切换
        storeIdChange(value) {
            const selectedOption = this.storeOption.find(
                (item) => item.value === value
            );
            console.log("selectedOption", selectedOption, value, this.storeOption);
            this.storeId = value;
            this.queryParams.storeId = value;
            this.storeName = selectedOption.label;
        },
        searchRegionChange(value) {
            if (value) {
                this.queryParams.storeId = "";
            }
            fetchStoreList({ regionId: value }).then((res) => {
                this.searchStoreOption = res.data.map((rItem) => {
                    return {
                        label: rItem.storeName,
                        value: rItem.id,
                    };
                });
            });
        },
        getTime() {
            if (this.time && this.time.length != 0) {
                this.queryParams.startTime = this.time[0];
                this.queryParams.endTime = this.time[1];
                this.getList();
            } else {
                this.queryParams.startTime = "";
                this.queryParams.endTime = "";
                this.getList();
            }
        },
    },
};
</script>